

// 处理富文本编辑器中的base64图片
function processBase64Images(htmlContent, callback) {
	var processedHTML = htmlContent;
	var base64Regex = /src="data:image\/([^;]+);base64,([^"]+)"/g;
	var matches = [];
	var match;
	
	// 收集所有base64图片
	while ((match = base64Regex.exec(htmlContent)) !== null) {
		matches.push({
			fullMatch: match[0],
			imageType: match[1],
			base64Data: match[2]
		});
	}
	
	if (matches.length === 0) {
		callback(htmlContent);
		return;
	}
	
	var uploadCount = 0;
	var totalCount = matches.length;
	
	matches.forEach(function(img, index) {
		// 直接使用base64数据上传
		var base64String = "data:image/" + img.imageType + ";base64," + img.base64Data;
		
		$.ajax({
			url: ctx + 'common/uploadBase64',
			type: 'POST',
			data: base64String,
			async: false,
			contentType: 'application/json',
			success: function(response) {
				console.log("response：",response);
				if (response && response.code === 0) {
					// 替换base64为服务器URL - 使用字符串直接替换
					var searchString = img.fullMatch;
					var replaceString = 'src="' + response.url + '"';
					
					console.log("搜索字符串:", searchString.substring(0, 100) + "...");
					console.log("替换字符串:", replaceString);
					
					// 检查是否包含搜索字符串
					if (processedHTML.indexOf(searchString) !== -1) {
						processedHTML = processedHTML.replace(searchString, replaceString);
						console.log("替换成功");
					} else {
						console.log("搜索字符串未找到，尝试转义特殊字符");
						// 尝试转义特殊字符
						var escapedSearch = searchString.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
						var regex = new RegExp(escapedSearch, 'g');
						if (regex.test(processedHTML)) {
							processedHTML = processedHTML.replace(regex, replaceString);
							console.log("使用正则表达式替换成功");
						} else {
							console.log("转义后也未找到匹配项");
						}
					}
				} else {
					console.log("上传失败或响应格式不正确");
				}

				console.log("处理图片:", img.fullMatch.substring(0, 50) + "...");
				
				uploadCount++;
				if (uploadCount === totalCount) {
					console.log("所有图片处理完成，processedHTML：" + processedHTML);
					callback(processedHTML);
				}
			},
			error: function() {
				console.log('图片上传失败');
				uploadCount++;
				if (uploadCount === totalCount) {
					console.log("所有图片处理完成，processedHTML：" + processedHTML);
					callback(processedHTML);
				}
			}
		});
	});
}